package middlewares

import (
	"backend/form"
	"backend/utils"
	"encoding/json"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Permission(db *gorm.DB) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 跳过鉴权的路径
		skipPaths := []string{
			"/user/login",
			"/user/feishu/login",
			"/api/v1/register",
			"/mypermission/list",
		}

		for _, path := range skipPaths {
			if ctx.Request.URL.Path == path {
				ctx.Next()
				return
			}
		}

		// 获取用户
		email, ok := ctx.Get("email")
		if !ok {
			ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			ctx.Abort()
			return
		}
		result, err := utils.RDB.Get(ctx.Request.Context(), email.(string)).Result()
		if err != nil {
			ctx.JSON(http.StatusForbidden, gin.H{"error": err})
			ctx.Abort()
			return
		}
		var userData form.UserReids
		err = json.Unmarshal([]byte(result), &userData)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": err})
			ctx.Abort()
			return
		}

		// 如果是超级管理员，跳过权限判断
		if userData.Supper {
			ctx.Next()
			return
		}

		// 如果用户已禁用，则返回拒绝访问
		if !userData.Status {
			ctx.JSON(http.StatusForbidden, gin.H{"error": err})
			ctx.Abort()
			return
		}

		// 当前请求的路径和方法
		requestedPath := ctx.FullPath()
		requestedMethod := ctx.Request.Method

		// 检查是否有权限
		if allowedPaths, ok := userData.PermissionMap[requestedMethod]; ok {
			for _, allowedPath := range allowedPaths {
				if allowedPath == requestedPath {
					ctx.Next() //有权限
					return
				}
			}
		}

		// 如果没有匹配到权限
		ctx.JSON(http.StatusForbidden, gin.H{"error": "Forbidden"})
		ctx.Abort()
		return
	}
}
